import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Demo15 {
	public static void main(String[] args) throws IOException {
		Scanner scanner=new Scanner(System.in);
		System.out.println("输入要扫描的目录：");
		String directory= scanner.nextLine();
		File file=new File(directory);
		if(file.isFile()) {
			System.out.println("输入的是一个文件，输入有误");
			return ;
		}
		if(!file.isDirectory()) {
			System.out.println("输入的不是一个目录，输入有误");
			return ;
		}
		System.out.println("请输入指定字符");
		String word=scanner.nextLine();
		
		//输入完目录和指定字符的时候，
		List<File> list=new ArrayList<>();
		scanDir2(file,word,list);
		System.out.println(list.size());
	}

	private static void scanDir2(File file, String word, List<File> list)throws IOException {
		File[] files=file.listFiles();
		if(file==null||file.length() == 0) {
			return ;
		}
		for (File file1:files) {
			if(file1.isDirectory()) {
				scanDir2(file1,word,list);
			} else {
				if(ContainWord(file1,word,list)) {
					System.out.println("文件路径为："+file1.getAbsolutePath());
				}
			}
		}
	}

	private static boolean  ContainWord(File file1, String word, List<File> list)throws IOException {
		StringBuilder stringBuilder=new StringBuilder();
		try(InputStream inputStream= Files.newInputStream(file1.toPath())) {
			try(Scanner scanner=new Scanner(inputStream)) {
				while(scanner.hasNextLine()) {
					stringBuilder.append(scanner.nextLine());
					stringBuilder.append("\r\n");
				}
			}
		}
		return stringBuilder.indexOf(word)!=-1;
	}

}
